package utils

import "strings"

/*
00:00-07:00,08:00-10:00,11:00-12:00
多线程不安全
*/
type MultiStringSection struct {
	rawSections []string
	startlist   []string
	endlist     []string
}

func NewMultiStringSection(exp string) *MultiStringSection {
	rval := &MultiStringSection{}
	rval.Parse(exp)
	return rval
}

func (this *MultiStringSection) Count() int {
	return len(this.startlist)
}

func (this *MultiStringSection) String() string {
	var sb BytesBuilder
	for k, v := range this.rawSections {
		if k > 0 {
			sb.AppendStr(",")
		}
		sb.AppendStr(v)
	}
	return sb.String()
}

func (this *MultiStringSection) Parse(exp string) {
	sections := strings.Split(exp, ",")
	if len(sections) == 1 {
		sections = strings.Split(exp, ";")
	}
	if len(sections) == 1 {
		sections = strings.Split(exp, " ")
	}
	this.startlist = make([]string, 0, len(sections))
	this.endlist = make([]string, 0, len(sections))
	this.rawSections = make([]string, 0, len(sections))
	for i := 0; i < len(sections); i++ {
		str := Trim(sections[i])
		if len(str) == 0 {
			continue
		}
		this.rawSections = append(this.rawSections, str)
		itms := strings.SplitN(str, "-", 2)
		if len(itms) == 1 {
			itms = strings.SplitN(str, "~", 2)
		}
		this.startlist = append(this.startlist, itms[0])
		if len(itms) == 1 {
			this.endlist = append(this.endlist, "")
		} else {
			this.endlist = append(this.endlist, itms[1])

		}
	}
}

func (this *MultiStringSection) IsIn(s string) string {
	s = Trim(s)
	for i := 0; i < len(this.startlist); i++ {
		if s >= this.startlist[i] && s <= this.endlist[i] {
			return this.rawSections[i]
		}
	}
	return ""
}
